const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const compression = require('compression');
const morgan = require('morgan');
const path = require('path');

// 导入路由模块
const authRoutes = require('./auth');
const userRoutes = require('./users');
const courseRoutes = require('./courses');
const examRoutes = require('./exams');

// 导入中间件
const { authenticate } = require('../middleware/auth');
const requestLogger = require('../middleware/requestLogger');
const responseTime = require('../middleware/responseTime');
const notFound = require('../middleware/notFound');
const errorHandler = require('../middleware/errorHandler');

// 导入配置
const config = require('../config/config');
const logger = require('../config/logger');

const router = express.Router();

// 全局中间件配置
const setupMiddleware = (app) => {
  // 安全中间件
  app.use(helmet({
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        styleSrc: ["'self'", "'unsafe-inline'"],
        scriptSrc: ["'self'"],
        imgSrc: ["'self'", "data:", "https:"],
        connectSrc: ["'self'"],
        fontSrc: ["'self'"],
        objectSrc: ["'none'"],
        mediaSrc: ["'self'"],
        frameSrc: ["'none'"]
      }
    },
    crossOriginEmbedderPolicy: false
  }));

  // CORS配置
  app.use(cors({
    origin: config.cors.origin,
    credentials: config.cors.credentials,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
    exposedHeaders: ['X-Total-Count', 'X-Response-Time']
  }));

  // 压缩响应
  app.use(compression({
    filter: (req, res) => {
      if (req.headers['x-no-compression']) {
        return false;
      }
      return compression.filter(req, res);
    },
    threshold: 1024
  }));

  // 请求体解析
  app.use(express.json({ 
    limit: config.upload.maxFileSize,
    verify: (req, res, buf) => {
      req.rawBody = buf;
    }
  }));
  app.use(express.urlencoded({ 
    extended: true, 
    limit: config.upload.maxFileSize 
  }));

  // 静态文件服务
  app.use('/uploads', express.static(path.join(process.cwd(), 'uploads'), {
    maxAge: '1d',
    etag: true,
    lastModified: true
  }));

  // 请求日志
  if (config.env === 'development') {
    app.use(morgan('dev'));
  } else {
    app.use(morgan('combined', {
      stream: {
        write: (message) => logger.info(message.trim())
      }
    }));
  }

  // 自定义中间件
  app.use(requestLogger);
  app.use(responseTime);
};

// 速率限制配置
const createRateLimit = (windowMs, max, message) => {
  return rateLimit({
    windowMs,
    max,
    message: {
      success: false,
      message,
      retryAfter: Math.ceil(windowMs / 1000)
    },
    standardHeaders: true,
    legacyHeaders: false,
    handler: (req, res) => {
      logger.warn('速率限制触发', {
        ip: req.ip,
        userAgent: req.get('User-Agent'),
        path: req.path,
        method: req.method
      });
      
      res.status(429).json({
        success: false,
        message,
        retryAfter: Math.ceil(windowMs / 1000)
      });
    }
  });
};

// 不同类型的速率限制
const rateLimits = {
  // 全局限制
  global: createRateLimit(
    15 * 60 * 1000, // 15分钟
    1000, // 1000次请求
    '请求过于频繁，请稍后再试'
  ),
  
  // 认证相关限制
  auth: createRateLimit(
    15 * 60 * 1000, // 15分钟
    10, // 10次尝试
    '登录尝试过于频繁，请15分钟后再试'
  ),
  
  // 文件上传限制
  upload: createRateLimit(
    60 * 60 * 1000, // 1小时
    50, // 50次上传
    '文件上传过于频繁，请1小时后再试'
  ),
  
  // API调用限制
  api: createRateLimit(
    15 * 60 * 1000, // 15分钟
    500, // 500次请求
    'API调用过于频繁，请稍后再试'
  )
};

// 健康检查路由
router.get('/health', (req, res) => {
  const healthCheck = {
    uptime: process.uptime(),
    message: 'OK',
    timestamp: new Date().toISOString(),
    environment: config.env,
    version: process.env.npm_package_version || '1.0.0',
    memory: process.memoryUsage(),
    cpu: process.cpuUsage()
  };
  
  res.json({
    success: true,
    data: healthCheck
  });
});

// API信息路由
router.get('/info', (req, res) => {
  res.json({
    success: true,
    data: {
      name: 'RX在线教育平台API',
      version: '1.0.0',
      description: '提供用户管理、课程管理、考试管理等功能的RESTful API',
      environment: config.env,
      documentation: '/api/docs',
      endpoints: {
        auth: '/api/auth',
        users: '/api/users',
        courses: '/api/courses',
        exams: '/api/exams'
      },
      features: [
        '用户认证与授权',
        '课程管理',
        '考试系统',
        '文件上传',
        '数据统计',
        '日志记录',
        '缓存支持',
        '速率限制'
      ]
    }
  });
});

// API文档路由（简单版本）
router.get('/docs', (req, res) => {
  res.json({
    success: true,
    data: {
      title: 'RX在线教育平台API文档',
      version: '1.0.0',
      baseUrl: `${req.protocol}://${req.get('host')}/api`,
      authentication: {
        type: 'Bearer Token',
        header: 'Authorization',
        format: 'Bearer <token>'
      },
      endpoints: {
        '/auth': {
          description: '用户认证相关接口',
          methods: ['POST'],
          routes: {
            'POST /auth/register': '用户注册',
            'POST /auth/login': '用户登录',
            'POST /auth/logout': '用户登出',
            'POST /auth/refresh': '刷新令牌',
            'POST /auth/forgot-password': '忘记密码',
            'POST /auth/reset-password': '重置密码',
            'GET /auth/me': '获取当前用户信息'
          }
        },
        '/users': {
          description: '用户管理相关接口',
          methods: ['GET', 'PUT', 'DELETE'],
          routes: {
            'GET /users': '获取用户列表',
            'GET /users/:id': '获取用户详情',
            'PUT /users/:id': '更新用户信息',
            'DELETE /users/:id': '删除用户',
            'POST /users/:id/upload-avatar': '上传头像'
          }
        },
        '/courses': {
          description: '课程管理相关接口',
          methods: ['GET', 'POST', 'PUT', 'DELETE'],
          routes: {
            'GET /courses': '获取课程列表',
            'GET /courses/:id': '获取课程详情',
            'POST /courses': '创建课程',
            'PUT /courses/:id': '更新课程',
            'DELETE /courses/:id': '删除课程',
            'POST /courses/:id/publish': '发布课程'
          }
        },
        '/exams': {
          description: '考试管理相关接口',
          methods: ['GET', 'POST', 'PUT', 'DELETE'],
          routes: {
            'GET /exams': '获取考试列表',
            'GET /exams/:id': '获取考试详情',
            'POST /exams': '创建考试',
            'PUT /exams/:id': '更新考试',
            'DELETE /exams/:id': '删除考试',
            'POST /exams/:id/start': '开始考试',
            'POST /exams/:id/submit': '提交考试'
          }
        }
      },
      responseFormat: {
        success: {
          success: true,
          data: {},
          message: 'string (optional)'
        },
        error: {
          success: false,
          message: 'string',
          errors: ['array (optional)'],
          code: 'string (optional)'
        }
      },
      statusCodes: {
        200: 'OK - 请求成功',
        201: 'Created - 资源创建成功',
        400: 'Bad Request - 请求参数错误',
        401: 'Unauthorized - 未授权',
        403: 'Forbidden - 禁止访问',
        404: 'Not Found - 资源不存在',
        422: 'Unprocessable Entity - 验证失败',
        429: 'Too Many Requests - 请求过于频繁',
        500: 'Internal Server Error - 服务器内部错误'
      }
    }
  });
});

// 路由配置
const setupRoutes = (app) => {
  // 应用全局速率限制
  app.use('/api', rateLimits.global);
  
  // 基础路由
  app.use('/api', router);
  
  // 认证路由（特殊速率限制）
  app.use('/api/auth', rateLimits.auth, authRoutes);
  
  // 用户路由
  app.use('/api/users', rateLimits.api, userRoutes);
  
  // 课程路由
  app.use('/api/courses', rateLimits.api, courseRoutes);
  
  // 考试路由
  app.use('/api/exams', rateLimits.api, examRoutes);
  
  // 根路径重定向
  app.get('/', (req, res) => {
    res.redirect('/api/info');
  });
  
  // 404处理
  app.use('*', notFound);
  
  // 错误处理
  app.use(errorHandler);
};

// 优雅关闭处理
const setupGracefulShutdown = (server) => {
  const gracefulShutdown = (signal) => {
    logger.info(`收到${signal}信号，开始优雅关闭服务器...`);
    
    server.close((err) => {
      if (err) {
        logger.error('服务器关闭时发生错误:', err);
        process.exit(1);
      }
      
      logger.info('服务器已优雅关闭');
      process.exit(0);
    });
    
    // 强制关闭超时
    setTimeout(() => {
      logger.error('强制关闭服务器');
      process.exit(1);
    }, 10000);
  };
  
  process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
  process.on('SIGINT', () => gracefulShutdown('SIGINT'));
};

// 未捕获异常处理
const setupErrorHandlers = () => {
  process.on('uncaughtException', (err) => {
    logger.error('未捕获的异常:', err);
    process.exit(1);
  });
  
  process.on('unhandledRejection', (reason, promise) => {
    logger.error('未处理的Promise拒绝:', { reason, promise });
    process.exit(1);
  });
};

// 导出配置函数
module.exports = {
  setupMiddleware,
  setupRoutes,
  setupGracefulShutdown,
  setupErrorHandlers,
  rateLimits
};